const { Controller } = require("egg");

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    // const { id } = ctx.query;
    await ctx.render("index.html", {
      title: "Hello World",
    });
    // ctx.body = {
    //   code: 0,
    //   content: id,
    // };
  }
  async getUserInfo() {
    const { ctx } = this;
    const { id } = ctx.params;
    ctx.body = {
      code: 0,
      content: id,
    };
  }
  async createUser() {
    const { ctx } = this;
    const { name, age } = ctx.request.body;
    ctx.body = {
      code: 0,
      info: {
        name,
        age,
      },
    };
  }
  async user() {
    const { ctx } = this;
    const result = await ctx.service.home.user();
    ctx.body = result;
  }
  async addUser() {
    const { ctx } = this;
    const { name, age, height } = ctx.request.body;
    try {
      const result = await ctx.service.home.addUser(name, age, height);
      ctx.body = {
        code: 200,
        msg: "添加成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: "添加失败",
        data: null,
      };
    }
  }
  // 编辑
  async editUser() {
    const { ctx } = this;
    const { name, age, height } = ctx.request.body;
    try {
      const result = await ctx.service.home.editUser(name, age, height);
      ctx.body = {
        code: 200,
        msg: "添加成功",
        data: result,
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: "添加失败",
        data: null,
      };
    }
  }
  // 删除
  async deleteUser() {
    const { ctx } = this;
    const { name } = ctx.query;
    console.log("name=========>", name);
    try {
      const result = await ctx.service.home.deleteUser(name);
      ctx.body = {
        code: 200,
        msg: "删除成功",
      };
    } catch (error) {
      ctx.body = {
        code: 500,
        msg: "删除失败",
      };
    }
  }
}

module.exports = HomeController;
